package ag.script.project.standard.download;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.net.URLEncodeUtil;
import cn.hutool.core.util.StrUtil;
import okhttp3.*;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;

public class DownloadRes {

    private final String baseUrl;


    private String projectMkdir;

    public DownloadRes() {
        this.baseUrl = "https://gitee.com/ag-tools/ag-app-res/raw/master/ag-apps";
        this.projectMkdir = "/sdcard/Pictures";
    }


    public DownloadRes(String projectMkdir) {
        this.baseUrl = "https://gitee.com/ag-tools/ag-app-res/raw/master/ag-apps";
        this.projectMkdir = projectMkdir;
    }

    public DownloadRes(String baseUrl, String projectMkdir) {
        this.baseUrl = baseUrl;
        this.projectMkdir = projectMkdir;
    }

    public boolean downloadEnsure(String shortUrl) {
        if (StrUtil.isBlankIfStr(shortUrl)) {
            return false;
        }
        String projectName = StrUtil.subBefore(StrUtil.removePrefix(StrUtil.replace(shortUrl, "\\", "/"), "/"), "/", false);
        System.out.println("项目名称:" + projectName);

        File destFilePath = new File(projectMkdir, shortUrl);
        FileUtil.mkParentDirs(destFilePath);
        System.out.println("输出路径:" + destFilePath.getAbsolutePath());


        //只确认下载三次，如果下载失败则返回false
        for (int i = 0; i < 3; i++) {
            try {
                OkHttpClient okHttpClient = new OkHttpClient();

                String url = baseUrl + StrUtil.addPrefixIfNot(URLEncodeUtil.encode(shortUrl), "/");
                System.out.println("下载链接:" + url);

                Request request = new Request.Builder()
                        .url(url)
                        .get()
                        .build();

                Call call = okHttpClient.newCall(request);
                //开始获取
                Response response = call.execute();

                if (response.isSuccessful()) {
                    ResponseBody body = response.body();
                    if (body == null) {
                        continue;
                    }
                    //long total = body.contentLength();//获取文件总大小
                    InputStream inputStream = body.byteStream();

                    IoUtil.copy(inputStream, new FileOutputStream(destFilePath));
                    return true;
                }
            } catch (Throwable ignore) {
            }
        }

        return false;
    }


}
